using System.Diagnostics;
using System.Security.Claims;
using System;
using System.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

using Read.Models;
using Read.Services;
using Read.Utility;

namespace Read.Web.Admin
{
    /// <summary>
    /// AdminBaseController
    /// </summary>
    [Area("Admin")]
    //[Authorize]
    public class AdminBaseController : Controller
    {
        /// <summary>
        /// OnActionExecuting
        /// </summary>
        /// <param name="context"></param>
        /// [AllowAnonymous]
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            HttpRequest httpRequest = context.HttpContext.Request;
            if (!User.Identity.IsAuthenticated)
            {
                if (httpRequest.IsAjaxRequest())
                {
                    context.Result = Json(new ResultData<string>() { Result = false, Code = -1, Message = "未登录" });
                    return;
                }
                else
                {
                    //var result = new ViewResult { ViewName = "Login" };
                    //Controller cb = context.Controller as Controller;
                    //context.Result = cb.Content("未登录");
                    //context.Result = Redirect("/Account/Login");
                    //context.Result = new RedirectResult(string.Format("/Admin/Account/Login?ReturnUrl={0}", HttpUtility.UrlEncode("/Admin")));
                    string url = context.HttpContext.Content("~/Admin/Account/Login");
                    url = string.Concat(url, "?ReturnUrl=", httpRequest.Path);
                    RedirectResult redirectResult = new RedirectResult(url);
                    context.Result = redirectResult;
                    return;
                }
            }
            else
            {
                string controller = context.RouteData.Values["controller"].ToString();
                string action = context.RouteData.Values["action"].ToString();
                string role = User.FindFirst(ClaimTypes.Role).Value;
                if (role != "1")
                {
                    var access = new AccessService();
                    if (access.getAccess(role, controller, action) == null)
                    {
                        //context.Result = Redirect("/Admin/Account/AccessDenied");
                        Controller cb = context.Controller as Controller;
                        context.Result = Json(new ResultData<string>() { Result = false, Code = -1, Message = "当前角色无权操作" });
                        //context.Result = cb.Content(string.Format("没权限,当前控制器:{0},方法:{1},角色:{2}", controller, action, role));
                    }
                }
                //Controller cb = context.Controller as Controller;
                //context.Result = cb.Content(string.Format("控制器:{0},方法:{1},角色:{2}", controller, action, role));
            }
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 获取当前后台用户的名称
        /// </summary>
        protected string IdentityName
        {
            get { return HttpContext.User.Identity.Name; }
        }

        /// <summary>
		/// 后台登录的用户数据
		/// </summary>
		protected AdminModel AdminUser
        {
            get
            {
                var userData = User.FindFirst(ClaimTypes.UserData).Value;
                return JsonConvert.DeserializeObject<AdminModel>(userData);
            }
        }

        /// <summary>
        /// JSON数据返回
        /// </summary>
        public JsonResult ResultJSON(bool result, object data = null, string message = "")
        {
            #region 操作日志
            string area = RouteData.Values["area"].ToString();
            string controller = RouteData.Values["controller"].ToString();
            string action = RouteData.Values["action"].ToString();
            string path = HttpContext.Request.Path.ToString();
            string method = Request.Method.ToUpper();
            string info = $"提示语:{message},模块:{area},控制器:{controller},方法:{action},请求方式:{method},Form参数:{HttpContext.Request.Form.ToJson()}";
            var service = new LogService();
            var log = new OperationLogModel();
            log.Uid = AdminUser.Id;
            log.Time = Tools.ToUnixTime();
            log.Ip = HttpContext.GetClientIP();
            log.Status = result;
            log.Info = info;
            log.Url = HttpContext.GetRequestUrl();
            service.operationLogAdd(log);
            #endregion
            //Console.WriteLine(info);
            return Json(data);
        }
    }
}